package com.ihighest.app.common.kit;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.RongIMClient.OnReceiveMessageListener;
import io.rong.imlib.model.Conversation.ConversationType;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.message.ImageMessage;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActivityManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.base.AbstractKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.activity.ImageViewActivity;
import com.ihighest.app.infox.im.SendMessageListener;
import com.ihighest.app.infox.tools.DataCleanManager;
import com.ihighest.app.infox.tools.LongTimeForData;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * App工具
 * 
 * @author lkx Created at 2015-11-24 下午3:51:56
 * @version 1.0
 */
public class AppKit extends AbstractKit {

	private static final long serialVersionUID = 494026367741641809L;

	static final String TAG = "AppKit";

	/**
	 * 强制退出App，通过System.exit Process.kill
	 */
	public static void forceExit(Context context) {

		System.exit(0);
	}

	/**
	 * 获取当前app所属的渠道
	 * 
	 * @param context
	 * @return
	 * 
	 * @author Vity Created at 2015-11-4 下午1:44:10
	 */
	public static String getChannel(Context context) {
		ApplicationInfo appinfo = context.getApplicationInfo();
		String sourceDir = appinfo.sourceDir;
		String ret = "";
		ZipFile zipfile = null;
		try {
			zipfile = new ZipFile(sourceDir);
			Enumeration<?> entries = zipfile.entries();
			while (entries.hasMoreElements()) {
				ZipEntry entry = ((ZipEntry) entries.nextElement());
				String entryName = entry.getName();
				if (entryName.startsWith("htchannel")) {
					ret = entryName;
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (zipfile != null) {
				try {
					zipfile.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		String[] split = ret.split("_");
		if (split != null && split.length >= 2) {
			return ret.substring(split[0].length() + 1);
		} else {
			return readMetaDataFromApplication(context, "UMENG_CHANNEL");
		}
	}

	/**
	 * 获得当前进程的名字
	 * 
	 * @param context
	 * @return 进程号
	 */
	public static String getCurProcessName(Context context) {

		int pid = android.os.Process.myPid();

		ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

		for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {

			if (appProcess.pid == pid) {
				return appProcess.processName;
			}
		}
		return null;
	}

	/**
	 * 建立与融云服务器的连接
	 * 
	 * @param token
	 */
	public static void connectRongIM(final Context context, String token) {
		if (context.getApplicationInfo().packageName.equals(AppKit.getCurProcessName(context.getApplicationContext()))) {

			RongIM.setOnReceiveMessageListener(new OnReceiveMessageListener() {

				@Override
				public boolean onReceived(Message message, int left) {
					// 聊天是否加入铃铛提示 是的话就发广播，不用就不发
					// Intent mIntent = new Intent(Const.CHANGECOUNT);
					// Const.UNREADMESSAGE++;
					// // 发送广播
					// context.sendBroadcast(mIntent);

					// Uri uri =
					// RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);//
					// 系统自带提示音
					// Ringtone rt = RingtoneManager.getRingtone(context, uri);
					// rt.play();

					/*
					 * 想设置震动大小可以通过改变pattern来设定，如果开启时间太短，震动效果可能感觉不到
					 */
					// Vibrator vibrator = (Vibrator)
					// context.getSystemService(Context.VIBRATOR_SERVICE);
					// long[] pattern = { 100, 400, 100, 400 }; // 停止 开启 停止 开启
					// // 如果只想震动一次，index设为-1
					// vibrator.vibrate(pattern, -1); // 重复两次上面的pattern

					System.out.println("extra         --> " + message.getExtra());
					System.out.println("messageId     --> " + message.getMessageId());
					System.out.println("getObjectName -->" + message.getObjectName());
					System.out.println("getReceivedTime -->" + message.getReceivedTime());

					System.out.println("getSenderUserId -->" + message.getSenderUserId());
					System.out.println("getTargetId -->" + message.getTargetId());
					System.out.println("getConversationType -->" + message.getConversationType().name());
					String extra = message.getExtra();
					if (message.getContent() instanceof TextMessage) {
						TextMessage msg = (TextMessage) message.getContent();
						extra = msg.getExtra();
					} else if (message.getContent() instanceof VoiceMessage) {
						VoiceMessage msg = (VoiceMessage) message.getContent();
						extra = msg.getExtra();
					} else if (message.getContent() instanceof ImageMessage) {
						ImageMessage msg = (ImageMessage) message.getContent();
						extra = msg.getExtra();
					}

					if (!Const.IS_CHAT) {
						if (TextUtils.isEmpty(extra)) {
							// 非自定义聊天框，简单对话
							if (message.getConversationType() == ConversationType.PRIVATE) {
								// 私聊
								JSONObject json = Api.data("member/info/r_" + message.getSenderUserId() + ".json", context);
								Const.IM_EXTRA = "";
								try {
									String title = (json != null && json.has("title") && !TextUtils.isEmpty(json.getString("title")) ? json
											.getString("title") : "访客");
									title = "与  " + title + " 对话中";

									RongIM.getInstance().startPrivateChat(context, message.getSenderUserId(), title);
									return true;
								} catch (Exception e) {
									return false;
								}
							} else if (message.getConversationType() == ConversationType.GROUP) {
								// 群聊
								JSONObject json = Api.data("chat/group/r_" + message.getTargetId() + ".json", context);
								Const.IM_EXTRA = "";
								try {
									RongIM.getInstance().startGroupChat(
											context,
											message.getTargetId(),
											(json != null && json.has("title") && !TextUtils.isEmpty(json.getString("title")) ? json
													.getString("title") : "群组聊天"));
									return true;
								} catch (Exception e) {
									return false;
								}

							}
						} else {
							if (message.getConversationType() == ConversationType.PRIVATE) {

								// 私聊

								// 回答问题 chat_issue:qid:mid

								// 追问 问题 chat_issue_ask:qid:aid:mid

								// 回复问题 chat_issue_reply:qid:aid:mid

								// JSONObject json = Api.data("member/info/r_" +
								// message.getSenderUserId() + ".json",
								// context);
								// try {
								// String[] extraArr = extra.split(":");
								//
								// if
								// (extraArr[0].equalsIgnoreCase("chat_issue"))
								// {
								// // 回答过来的
								// Const.IM_EXTRA = "chat_issue_ask" + ":" +
								// extraArr[1] + ":" + extraArr[2] + ":"
								// + SharedPreferencesKit.getString(context,
								// Const.SP_KEY_USER_MID);
								// } else if
								// (extraArr[0].equalsIgnoreCase("chat_issue_ask"))
								// {
								// // 追问过来的
								// Const.IM_EXTRA = "chat_issue_reply" + ":" +
								// extraArr[1] + ":" + extraArr[2] + ":"
								// + SharedPreferencesKit.getString(context,
								// Const.SP_KEY_USER_MID);
								// } else if
								// (extraArr[0].equalsIgnoreCase("chat_issue_reply"))
								// {
								// // 回复过来的
								// Const.IM_EXTRA = "chat_issue_ask" + ":" +
								// extraArr[1] + ":" + extraArr[2] + ":"
								// + SharedPreferencesKit.getString(context,
								// Const.SP_KEY_USER_MID);
								// }
								//
								// // Const.IM_EXTRA = _extra + ":" +
								// // json.getString("id");
								//
								// String title = (json != null &&
								// json.has("title") &&
								// !TextUtils.isEmpty(json.getString("title")) ?
								// json
								// .getString("title") : "访客");
								// if (extra.startsWith("chat_issue_reply")) {
								// title = "[" + title + "] 的提问";
								// } else if
								// (extra.startsWith("chat_issue_ask")) {
								// title = "[" + title + "] 的提问";
								// } else if (extra.startsWith("chat_issue")) {
								// title = "[" + title + "] 的回答";
								// }
								// RongIM.getInstance().startPrivateChat(context,
								// message.getSenderUserId(), title);
								// return true;
								// } catch (Exception e) {
								// return false;
								// }
								return true;
							} else if (message.getConversationType() == ConversationType.GROUP) {
								// 群聊
								// JSONObject json = Api.data("chat/group/r_" +
								// message.getTargetId() + ".json", context);
								//
								// try {
								// Const.IM_EXTRA = extra.substring(0,
								// extra.lastIndexOf(":")) + ":" +
								// json.getString("id");
								// RongIM.getInstance().startGroupChat(
								// context,
								// message.getTargetId(),
								// (json != null && json.has("title") &&
								// !TextUtils.isEmpty(json.getString("title")) ?
								// json
								// .getString("title") : "群组聊天"));
								// return true;
								// } catch (Exception e) {
								// return false;
								// }
								return true;
							}
						}
					} else {
						return true;
					}
					return false;
				}
			});

			/**
			 * IMKit SDK调用第二步,建立与服务器的连接
			 */
			RongIM.connect(token, new RongIMClient.ConnectCallback() {

				/**
				 * Token 错误，在线上环境下主要是因为 Token 已经过期，您需要向 App Server 重新请求一个新的
				 * Token
				 */
				@Override
				public void onTokenIncorrect() {
					Log.d("LoginActivity", "--onTokenIncorrect");
				}

				/**
				 * 连接融云成功
				 * 
				 * @param userid
				 *            当前 token
				 */
				@Override
				public void onSuccess(String userid) {
					Log.d("LoginActivity", "--onSuccess" + userid);
					RongIM.getInstance().setSendMessageListener(new SendMessageListener());
					AppKit.refreshRongIMUser(context);
					Const.IS_RONGIM_INIT = true;
				}

				/**
				 * 连接融云失败
				 * 
				 * @param errorCode
				 *            错误码，可到官网 查看错误码对应的注释
				 */
				@Override
				public void onError(RongIMClient.ErrorCode errorCode) {
					Log.d("LoginActivity", "--onError" + errorCode);
				}
			});
		}
	}

	/**
	 * 刷新用户信息
	 * 
	 * @author Vity Created at 2015-11-2 下午1:05:29
	 */
	public static void refreshRongIMUser(Context context) {
		if (TextUtils.isEmpty(SharedPreferencesKit.getString(context, Const.SP_KEY_USER_RID))) {
			RongIM.getInstance().refreshUserInfoCache(
					new UserInfo(SharedPreferencesKit.getString(context, Const.SP_KEY_USER_RID), SharedPreferencesKit.getString(context,
							Const.SP_KEY_USER_NAME), Uri.parse(SharedPreferencesKit.getString(context, Const.SP_KEY_USER_HEADER))));
		}
	}

	/**
	 * 存储当前登录用户信息
	 * 
	 * @param json
	 * 
	 * @author Vity Created at 2015-10-27 下午11:50:04
	 * @throws JSONException
	 */
	public static void storeUserInfo(Context context, JSONObject json) throws JSONException {
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_ID, json.getString("uid"));
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_MID, json.getString("mid"));
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_TOKEN, json.getString("token"));
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_NAME, json.getString("name"));
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_TOKEN_EXPIRE, Long.toString(json.getLong("expire")));
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_TYPE, json.getString("type"));
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_HEADER, json.getString("header"));
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_RID, json.getString("rid"));
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_RTOKEN, json.getString("rtoken"));
		refreshRongIMUser(context);
	}

	/**
	 * 清空当前登录用户信息
	 * 
	 * @author Vity Created at 2015-10-27 下午11:50:22
	 */
	public static void cleanUserInfo(Context context) {
		SharedPreferencesKit.putString(context, Const.SP_KEY_LAST_LOGIN_PWD, null);
		SharedPreferencesKit.putString(context, Const.USER_InvitedCode, null);
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_ID, null);
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_MID, null);
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_TOKEN, null);
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_NAME, null);
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_TOKEN_EXPIRE, null);
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_TYPE, null);
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_HEADER, null);
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_RID, null);
		SharedPreferencesKit.putString(context, Const.SP_KEY_USER_RTOKEN, null);
	}

	/**
	 * 清除缓存数据
	 * 
	 * @param context
	 * 
	 * @author Vity Created at 2015-11-1 上午3:49:13
	 */
	public static void cleanCache(Context context) {
		DataCleanManager.cleanExternalCache(context);
		DataCleanManager.cleanInternalCache(context);
	}

	/**
	 * 获取设备编码
	 * 
	 * @return
	 */
	public static String getDeviceCode(Context context) {
		String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
		TelephonyManager telephonyManager;
		telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String imeistring = telephonyManager.getDeviceId();
		String imsistring = telephonyManager.getSubscriberId();
		return md5(androidId + "||" + imeistring + "||" + imsistring);
	}

	/**
	 * 获取Android SDK 版本
	 * 
	 * @return
	 */
	public static String getSDKVersion() {
		return "API " + android.os.Build.VERSION.SDK_INT;
	}

	/**
	 * 获取手机型号
	 * 
	 * @return
	 */
	public static String getPhoneModel() {
		return android.os.Build.MODEL;
	}

	/**
	 * 获取Android 版本号
	 * 
	 * @return
	 */
	public static String getAndroidVersion() {
		return android.os.Build.VERSION.RELEASE;
	}

	/**
	 * 获取App VersionName
	 * 
	 * @param context
	 * @return
	 * 
	 * @author Vity Created at 2015-11-4 下午9:50:21
	 */
	public static String getAppVersionName(Context context) {
		try {
			return context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS).versionName;
		} catch (NameNotFoundException e) {
		}
		return "";
	}

	/**
	 * 获取 App VersionCode
	 * 
	 * @param context
	 * @return
	 * 
	 * @author Vity Created at 2015-11-4 下午9:51:02
	 */
	public static int getAppVersionCode(Context context) {
		try {
			return context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS).versionCode;
		} catch (NameNotFoundException e) {
		}
		return 1;
	}

	/**
	 * 获取MD5签名
	 * 
	 * @param source
	 * @return
	 */
	public static String md5(String source) {
		String s = null;
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			md.update(source.getBytes());
			byte tmp[] = md.digest();
			char str[] = new char[16 * 2];
			int k = 0;
			for (int i = 0; i < 16; i++) {
				byte byte0 = tmp[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];

			}
			s = new String(str);
		} catch (NoSuchAlgorithmException e) {
			Log.e(TAG, e.getMessage());
		}
		return s;
	}

	/**
	 * 获取几秒前、几分钟前
	 * 
	 * @param time
	 * @return
	 * 
	 * @author Vity Created at 2015-10-20 下午10:03:02
	 */
	public static String timeToBeforeStr(long time) {
		String result = "";
		long now = System.currentTimeMillis();
		if (now - time < 60 * 1000) {
			result = ((now - time) / 1000) + "秒前";
		} else if (now - time < 60 * 60 * 1000) {
			result = ((now - time) / (60 * 1000)) + "分钟前";
		} else if (now - time < 12 * 60 * 60 * 1000) {
			result = ((now - time) / (60 * 60 * 1000)) + "小时前";
		} else if (now - time < 24 * 60 * 60 * 1000) {
			result = LongTimeForData.transferLongToDate(time, "MM-dd HH:mm");
		} else if (now - time < 5 * 24 * 60 * 60 * 1000) {
			result = ((now - time) / (24 * 60 * 60 * 1000)) + "天前";
		} else {
			result = LongTimeForData.transferLongToDate(time);
		}
		return result;
	}

	/**
	 * 将时间改为固定格式
	 * 
	 * @param time
	 * @return
	 * 
	 * @author lkx Created at 2015-11-6 下午8:09:03
	 */
	public static String timeToDaTe(long time) {
		String result = "";

		result = LongTimeForData.transferLongToDate(time, "MM-dd HH:mm");

		return result;
	}

	/**
	 * 组合多个JSON数组
	 * 
	 * @return
	 * 
	 * @author Vity Created at 2015-10-20 下午10:48:07
	 * @throws JSONException
	 */
	public static JSONArray joinJSONArray(JSONArray... array) throws JSONException {
		JSONArray result = new JSONArray();
		for (JSONArray arr : array) {
			if (arr != null && arr.length() > 0) {
				for (int i = 0; i < arr.length(); i++) {
					result.put(arr.get(i));
				}
			}
		}
		return result;
	}

	/**
	 * 组合多个JSON数组
	 * 
	 * @return
	 * 
	 * @author Vity Created at 2015-10-20 下午10:48:07
	 * @throws JSONException
	 */
	public static JSONArray joinJSONArray(JSONArray array, JSONObject... obj) throws JSONException {
		for (JSONObject jsonObject : obj) {
			array.put(jsonObject);
		}
		return array;
	}

	/**
	 * 去除文字换行\r、回车\n、分页\f、制表符号\t，去除两端空格
	 * 
	 * @param str
	 * @return
	 * 
	 * @author Vity Created at 2015-11-5 上午12:19:09
	 */
	public static String trimString(String str) {
		return str.replace("\r", "").replace("\n", "").replace("\f", "").replace("\t", "  ").trim();
	}

	/**
	 * 展示大图
	 * 
	 * @param context
	 * @param imageUri
	 * 
	 * @author Vity Created at 2015-11-6 上午12:52:38
	 */
	public static void showBigImageView(Context context, ArrayList<String> imageUri) {
		// 窗口模式打开
		if (imageUri == null || imageUri.size() == 0) {
			ToastKit.showShort(context, "未获取到图片地址");
			return;
		}
		Intent intent = new Intent(context, ImageViewActivity.class);
		if (imageUri.size() > 1) {
			intent.putStringArrayListExtra("images", imageUri);
		} else {
			intent.putExtra("image", imageUri.get(0));
		}
		context.startActivity(intent);
	}

	/**
	 * 展示大图
	 * 
	 * @param context
	 * @param imageUri
	 * 
	 * @author Vity Created at 2015-11-6 上午12:52:38
	 */
	public static void showBigImageView(Context context, String imageUri) {
		// 窗口模式打开
		if (imageUri == null || TextUtils.isEmpty(imageUri)) {
			ToastKit.showShort(context, "未获取到图片地址");
			return;
		}
		Intent intent = new Intent(context, ImageViewActivity.class);
		intent.putExtra("image", imageUri);
		context.startActivity(intent);
	}

	/**
	 * 得到amr的时长
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 * 
	 * @author Vity Created at 2015-11-18 下午9:41:45
	 */
	public static int getAmrDuration(File file) throws IOException {
		long duration = -1;
		int[] packedSize = { 12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0, 0, 0 };
		RandomAccessFile randomAccessFile = null;
		try {
			randomAccessFile = new RandomAccessFile(file, "rw");
			long length = file.length();// 文件的长度
			int pos = 6;// 设置初始位置
			int frameCount = 0;// 初始帧数
			int packedPos = -1;

			byte[] datas = new byte[1];// 初始数据值
			while (pos <= length) {
				randomAccessFile.seek(pos);
				if (randomAccessFile.read(datas, 0, 1) != 1) {
					duration = length > 0 ? ((length - 6) / 650) : 0;
					break;
				}
				packedPos = (datas[0] >> 3) & 0x0F;
				pos += packedSize[packedPos] + 1;
				frameCount++;
			}

			duration += frameCount * 20;// 帧数*20
		} finally {
			if (randomAccessFile != null) {
				randomAccessFile.close();
			}
		}
		return (int) ((duration / 1000) + 1);
	}

	/**
	 * 文件转字节
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 * 
	 * @author Vity Created at 2015-11-18 下午9:41:36
	 */
	public static byte[] readToBytes(File file) throws IOException {
		byte[] buffer = new byte[(int) file.length()];
		InputStream ios = null;
		try {
			ios = new FileInputStream(file);
			if (ios.read(buffer) == -1) {
				throw new IOException("EOF reached while trying to read the whole file");
			}
		} finally {
			try {
				if (ios != null)
					ios.close();
			} catch (IOException e) {
			}
		}
		return buffer;
	}

	/**
	 * 字节转临时文件
	 * 
	 * @param b
	 * @param outputFile
	 * @return
	 * 
	 * @author Vity Created at 2015-11-18 下午10:33:22
	 */
	public static File getFileFromBytes(byte[] b) {
		BufferedOutputStream stream = null;
		File file = null;
		try {
			file = File.createTempFile("infox-tmp-", "");
			FileOutputStream fstream = new FileOutputStream(file);
			stream = new BufferedOutputStream(fstream);
			stream.write(b);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return file;
	}

	/**
	 * 读取application 节点 meta-data 信息
	 */
	public static String readMetaDataFromApplication(Context context, String name) {
		try {
			ApplicationInfo appInfo = context.getPackageManager()
					.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
			return appInfo.metaData.getString(name);

		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 插入融云消息
	 * 
	 * @param context
	 * @param cid
	 *            会话类型，1 private，3 group
	 * @param md
	 *            send 1 / receive 2
	 * @param senderId
	 * @param toId
	 * @param content
	 * @param msgType
	 * @param time
	 * 
	 * @author Vity Created at 2015-11-19 上午12:20:47
	 */
	public static void writeRongIMMessage(Context context, int cid, int md, String senderId, String toId, String content, String msgType,
			long time) {
		int CATEGORY_ID = cid; // 会话类型，1 private，3 group
		int MESSAGE_DIRECTION = md; // 1send / receive2
		int READ_STATUS = 1;
		int SEND_STATUS = 30;
		// System.out.println(context.getFilesDir().getPath());//
		// /data/data/com.ihighest.app.infox/files
		String RONG_CLOUD_STORAGE_MESSAGE_TABLE_NAME = "RCT_MESSAGE";// 数据库表
		String MESSAGE_STORAGE_PATH = context.getFilesDir().getPath() + "/" + readMetaDataFromApplication(context, "RONG_CLOUD_APP_KEY")
				+ "/" + RongIM.getInstance().getRongIMClient().getCurrentUserId() + "/storage";// 数据库路径
		SQLiteDatabase mSQLiteDatabase = SQLiteDatabase.openDatabase(MESSAGE_STORAGE_PATH, null, SQLiteDatabase.OPEN_READWRITE);
		ContentValues contentValues = new ContentValues();
		contentValues.put("TARGET_ID", toId);
		contentValues.put("CATEGORY_ID", CATEGORY_ID);
		contentValues.put("MESSAGE_DIRECTION", MESSAGE_DIRECTION);
		contentValues.put("READ_STATUS", READ_STATUS);
		contentValues.put("RECEIVE_TIME", time + 1);
		contentValues.put("SEND_TIME", time);
		contentValues.put("CLAZZ_NAME", msgType);
		contentValues.put("CONTENT", content);
		contentValues.put("SEND_STATUS", SEND_STATUS);
		contentValues.put("SENDER_ID", senderId);
		contentValues.put("EXTRA_COLUMN1", 1);
		contentValues.put("EXTRA_COLUMN2", 0);
		contentValues.put("EXTRA_COLUMN3", 0);
		long x = mSQLiteDatabase.insert(RONG_CLOUD_STORAGE_MESSAGE_TABLE_NAME, null, contentValues);

		System.out.println("x --> " + x);
	}

	/**
	 * 设置用户头像
	 * 
	 * @param url
	 *            图片地址
	 * @param image
	 *            图片控件
	 * 
	 * @author lkx Created at 2015-11-20 下午4:26:19
	 */
	public static void SetUserImg(String url, ImageView image) {
		DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.infox_person_no_icon)
				.showImageOnFail(R.drawable.infox_person_no_icon).showImageOnLoading(R.drawable.infox_person_no_icon).cacheInMemory(true)
				.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
		url = url + "?" + System.currentTimeMillis();
		ImageLoader.getInstance().displayImage(url, image, defaultOptions);
	};

	/**
	 * 设置普通图片
	 * 
	 * @param url
	 *            图片地址
	 * @param image
	 *            图片控件
	 * 
	 * @author lkx Created at 2015-11-20 下午4:26:59
	 */
	public static void SetNormalImg(String url, ImageView image) {

		ImageLoader.getInstance().displayImage(url, image);
	};

	public boolean appIsRunning() {
		return false;

	}

	/**
	 * 把list转换为一个用逗号分隔的字符串
	 * 
	 * @param list
	 *            需要转换的list
	 * @return
	 * 
	 * @author lkx Created at 2015-11-24 下午3:52:01
	 */
	public static String listToString(List list) {
		StringBuilder sb = new StringBuilder();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				if (i < list.size() - 1) {
					sb.append(list.get(i) + ",");
				} else {
					sb.append(list.get(i));
				}
			}
		}
		return sb.toString();
	}
}
